﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;

namespace APMAWebConsole.PlanningPart
{
    public partial class Releases : System.Web.UI.Page
    {
        private const string ReleasesDataSourceKey = "ReleasesDataSourceKey";
        private const string ProjectsListKey = "ProjectsListKey";
        private const string IsEditModeKey = "IsEditModeKey";
        private const string IsUpdateKey = "IsUpdateKey";
        private const string IsViewModeKey = "IsViewModeKey";
        private const string IterationsListKey = "IterationsListKey";

        public DataTable DataSource
        {
            get
            {
                return ViewState[ReleasesDataSourceKey] != null
                           ? (DataTable)ViewState[ReleasesDataSourceKey]
                           : (DataTable)(ViewState[ReleasesDataSourceKey] = SiteMaster.Proxy.GetReleasesList());
            }

            set { ViewState[ReleasesDataSourceKey] = value; }
        }

        public DataTable ProjectsList
        {
            get
            {
                return ViewState[ProjectsListKey] != null
                           ? (DataTable)ViewState[ProjectsListKey]
                           : (DataTable)(ViewState[ProjectsListKey] = SiteMaster.Proxy.GetProjectsList());
            }

            set { ViewState[ProjectsListKey] = value; }
        }

        private DataTable IterationsList
        {
            get
            {
                if (ViewState[IterationsListKey] != null)
                    return (DataTable)ViewState[IterationsListKey];

                var table = SiteMaster.Proxy.GetIterationsList();

                var expression = "Release_id <> " + DataSource.Rows[SelectedRow]["Id"];

                var foundRows = table.Select(expression);

                foreach (var dataRow in foundRows)
                    table.Rows.Remove(dataRow);

                ViewState[IterationsListKey] = table;

                return (DataTable)ViewState[IterationsListKey];
            }

            set { ViewState[IterationsListKey] = value; }
        }

        public bool IsEditMode
        {
            set { ViewState[IsEditModeKey] = value; }
            get { return ViewState[IsEditModeKey] != null && (bool) ViewState[IsEditModeKey]; }
        }

        public bool IsViewMode
        {
            set { ViewState[IsViewModeKey] = value; }
            get { return ViewState[IsViewModeKey] != null && (bool)ViewState[IsViewModeKey]; }
        }

        public bool IsUpdate
        {
            set { ViewState[IsUpdateKey] = value; }
            get { return ViewState[IsUpdateKey] != null && (bool)ViewState[IsUpdateKey]; }
        }

        private int SelectedRow
        {
            get
            {
                int selectedRow;
                var isSuccessfully = int.TryParse(txtSelectedRelease.Text, out selectedRow);

                if (isSuccessfully && selectedRow - 1 >= 0 && selectedRow - 1 < DataSource.Rows.Count 
                        && DataSource.Rows[selectedRow - 1] != null)
                    return selectedRow - 1;

                return -1;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.User.Identity.IsAuthenticated)
                Response.Redirect("~/Account/Login.aspx");
        }

        private void Rebind()
        {
            if (IsEditMode)
            {
                txtReleaseId.Enabled = false;

                ddlReleaseProjectId.Enabled = txtReleaseStartDate.Enabled = txtReleaseEndDate.Enabled =
                                                                                ddlReleaseStateId.Enabled =
                                                                                txtReleasePlanEstimate.Enabled =
                                                                                 btnCreateUpdate.Visible = !IsViewMode;

                ddlReleaseProjectId.Items.Clear();
                ddlReleaseProjectId.DataValueField = "Id";
                ddlReleaseProjectId.DataTextField = "Name";
                ddlReleaseProjectId.DataSource = ProjectsList;
                ddlReleaseProjectId.DataBind();
                ddlReleaseProjectId.Items.Insert(0, new ListItem(String.Empty, String.Empty));

                ddlReleaseStateId.Items.Clear();
                ddlReleaseStateId.DataValueField = "Id";
                ddlReleaseStateId.DataTextField = "Name";
                ddlReleaseStateId.Items.Insert(0, new ListItem(String.Empty, String.Empty));
                ddlReleaseStateId.Items.Insert(1, new ListItem("Planning", "7"));
                ddlReleaseStateId.Items.Insert(2, new ListItem("Active", "8"));
                ddlReleaseStateId.Items.Insert(3, new ListItem("Accepted", "9"));

                if (!IsUpdate)
                {
                    txtReleaseId.Text = txtReleasePlanEstimate.Text = "";
                    ddlReleaseProjectId.SelectedIndex = 0;
                    ddlReleaseStateId.SelectedIndex = 0;
                }
                else
                {
                    var selectedRow = SelectedRow;

                    if (selectedRow == -1)
                        return;

                    txtReleaseId.Text = DataSource.Rows[selectedRow]["Id"].ToString();
                    DateTime dateTimeParseValue;

                    var isParsed = DateTime.TryParse(DataSource.Rows[selectedRow]["Start_date"].ToString(), out dateTimeParseValue);
                    txtReleaseStartDate.Text = isParsed ? dateTimeParseValue.ToShortDateString() : "";
                    isParsed = DateTime.TryParse(DataSource.Rows[selectedRow]["End_date"].ToString(), out dateTimeParseValue);
                    txtReleaseEndDate.Text = isParsed ? dateTimeParseValue.ToShortDateString() : "";
                    txtReleasePlanEstimate.Text = DataSource.Rows[selectedRow]["Plan_estimate"].ToString();

                    ddlReleaseProjectId.SelectedValue = DataSource.Rows[selectedRow]["Project_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["Project_id"].ToString()
                                                            : null;

                    ddlReleaseStateId.SelectedValue = DataSource.Rows[selectedRow]["State_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["State_id"].ToString()
                                                            : null;
                }

                grdIterations.Visible = IsViewMode;
                if (IsViewMode)
                {
                    grdIterations.DataSource = IterationsList;
                    grdIterations.DataBind();
                }
            }
            else
            {
                grdReleases.DataSource = DataSource;
                grdReleases.DataBind();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            divEditMode.Visible = IsEditMode;
            divReleasesGrid.Visible = !IsEditMode;

            btnAddRelease.Visible = !IsEditMode;
            btnEditRelease.Visible =
                btnRemoveRelease.Visible = btnViewRelease.Visible = false;

            btnBackToList.Visible = IsEditMode;

            if (IsEditMode)
            {
                btnCreateUpdate.Text = IsUpdate ? "Update" : "Create";
            }

            Rebind();
        }

        protected void OnButtonCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Add":
                    {
                        IsEditMode = true;
                        IsUpdate = false;

                        break;
                    }
                case "Remove":
                    {
                        if (e.CommandArgument.ToString() != "")
                            txtSelectedRelease.Text = e.CommandArgument.ToString();

                        RemoveRelease();

                        break;
                    }
                case "Edit":
                    {
                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = false;

                        break;
                    }

                case "Select":
                    {
                        txtSelectedRelease.Text = e.CommandArgument.ToString();
                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = false;

                        break;
                    }

                case "View":
                    {
                        if (e.CommandArgument.ToString() != "")
                            txtSelectedRelease.Text = e.CommandArgument.ToString();

                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = true;
                        IterationsList = null;

                        break;
                    }

                case "SaveUpdate":
                    {
                        if (IsEditMode)
                        {
                            if (IsUpdate)
                            {
                                UpdateRelease();
                            }
                            else
                            {
                                SaveRelease();
                            }
                        }

                        break;
                    }

                case "BackToList":
                    {
                        IsEditMode = false;
                        IterationsList = null;

                        break;
                    }
            }
        }

        private Dictionary<string, object> PrepareParameters(Dictionary<string, object> parameters)
        {
            int intParseValue;

            var isParsed = int.TryParse(ddlReleaseProjectId.SelectedValue, out intParseValue);
            parameters.Add("Project_id", isParsed ? (int?)intParseValue : null);

            parameters.Add("Start_date", txtReleaseStartDate.Text);

            parameters.Add("End_date", txtReleaseEndDate.Text);

            isParsed = int.TryParse(ddlReleaseStateId.SelectedValue, out intParseValue);
            parameters.Add("State_id", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(txtReleasePlanEstimate.Text, out intParseValue);
            parameters.Add("Plan_estimate", isParsed ? (int?)intParseValue : null);

            return parameters;
        }

        private bool ValidateFields()
        {
            return Page.IsValid;
        }

        private void SaveRelease()
        {
            if (!ValidateFields())
                return;

            var parameters = PrepareParameters(new Dictionary<string, object>());

            SiteMaster.Proxy.AddNewRelease(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }

        private void UpdateRelease()
        {
            if (!ValidateFields())
                return;

            var parameters = new Dictionary<string, object>();

            int intParseValue;
            var isParsed = int.TryParse(txtReleaseId.Text, out intParseValue);

            if (!isParsed)
                return;

            parameters.Add("Id", intParseValue);

            parameters = PrepareParameters(parameters);

            SiteMaster.Proxy.UpdateRelease(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }

        private void RemoveRelease()
        {
            var selectedRow = SelectedRow;

            if (selectedRow == -1)
                return;

            int intParseValue;
            var isParsed = int.TryParse(DataSource.Rows[selectedRow]["Id"].ToString(), out intParseValue);

            if (!isParsed)
                return;

            SiteMaster.Proxy.RemoveRelease(intParseValue, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }
    }
}